<template>
  <img v-lazy="src" loading="lazy" decoding="async" alt="沒有圖片" v-error="'http://i.giphy.com/3og0ISeflb7vrNzy2A.gif'">
</template>

<script>
export default {
  name: "image-lazy",
  props: {
    src: {
      type: String,
      default: ''
    }
  },
  directives: {
    'lazy': {
      bind(el, binding) {
        // 设置loading图片地址: 可自行替换
        el.setAttribute('src', 'http://i.giphy.com/3og0ISeflb7vrNzy2A.gif');
        // 真实图片地址
        el.setAttribute('data-src', binding.value);
        const observer = new IntersectionObserver((entries, observer) => {
          entries.forEach((entry) => {
            // 目标元素进入可视区域
            if (entry.isIntersecting) {
              // 获取目标元素
              var img = entry.target;
              // 将img的src替换成真实图片地址
              img.src = img.dataset.src;
              // 结束观察该img元素
              observer.unobserve(img);
            }
          });
        });
        // 开始观察目标img元素
        observer.observe(el);
      }
    },
    'error': {
      bind(el, binding) {
        el.onerror = () => {
          el.src =  binding.value ? binding.value : 'http://i.giphy.com/3og0ISeflb7vrNzy2A.gif';
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
